// index.js
Page({
  data: {
    device_online: true,
    f_btn: false,
    lgt_p: false,
    human_detect: false,
    humid_data: '--',
    temp_data: '--'
  },

  config: {
    auth_info: "version=2022-05-01&res=userid%2F439596&et=2054270651&method=sha1&sign=OmARsEAF0%2BXIV0VW6kg6DGWeeWk%3D",
    product_id: "ZwQ1ozNTiF",
    device_name: "DHT11",
    api_base_url: "https://iot-api.heclouds.com"
  },

  onLoad() {
    this.fetchDeviceProperties();
    this.refreshTimer = setInterval(() => {
      this.fetchDeviceProperties();
    }, 5000);
  },

  onUnload() {
    clearInterval(this.refreshTimer);
  },

  fetchDeviceProperties() {
    wx.request({
      url: `${this.config.api_base_url}/thingmodel/query-device-property`,
      method: "GET",
      header: { 'Authorization': this.config.auth_info },
      data: {
        product_id: this.config.product_id,
        device_name: this.config.device_name
      },
      success: (res) => {
        console.log('API响应:', res.data);
        if (res.data?.code === 0) {
          this.updateDeviceData(res.data.data);
        }
      },
      fail: (err) => {
        console.error('请求失败:', err);
        this.setData({ device_online: false });
      }
    });
  },

  updateDeviceData(apiData) {
    const newData = {
      device_online: true,
      f_btn: this.getPropertyValue(apiData, 'f_btn') === 'true',
      lgt_p: this.getPropertyValue(apiData, 'lgt_p') === 'true',
      human_detect: this.getPropertyValue(apiData, 'human_detect') === 'true',
      humid_data: this.getPropertyValue(apiData, 'humid') || '--',
      temp_data: this.getPropertyValue(apiData, 'temp') || '--'
    };
    
    console.log('更新数据:', newData);
    this.setData(newData);
  },

  getPropertyValue(data, identifier) {
    const item = data.find(item => item?.identifier === identifier);
    return item?.value?.toString();
  },

  setDeviceProperty(event) {
    const param = event.currentTarget.dataset.param;
    const value = event.detail.value;
    
    // 立即更新UI状态
    this.setData({ [param]: value });
    
    // 显示"设置中"提示框，1秒后自动隐藏
    wx.showLoading({ 
        title: '设置中...', 
        mask: true,
        duration: 1000  // 设置1秒后自动隐藏
    });
    // 创建控制请求数据
    const createRequest = () => {
        return {
            product_id: this.config.product_id,
            device_name: this.config.device_name,
            params: { [param]: value }
        };
    };
    // 1秒后显示"设置成功"，无论实际结果如何
    setTimeout(() => {
        wx.hideLoading();
        wx.showToast({ 
            title: '设置成功', 
            icon: 'success',
            duration: 2000
        });
    }, 1000);
    // 发送第一次请求
    wx.request({
        url: `${this.config.api_base_url}/thingmodel/set-device-property`,
        method: "POST",
        header: { 'Authorization': this.config.auth_info },
        data: createRequest(),
        complete: () => {
            // 发送第二次请求
            wx.request({
                url: `${this.config.api_base_url}/thingmodel/set-device-property`,
                method: "POST",
                header: { 'Authorization': this.config.auth_info },
                data: createRequest(),
                complete: () => {
                    // 刷新状态
                    this.fetchDeviceProperties();
                }
            });
        }
    });
}
});
